﻿using System.Text;
using MQTTnet;
using MQTTnet.Server;
using NLog;
namespace TFMQTTService
{
    public class TFMQTT
    {
        ILogger logger = LogManager.GetCurrentClassLogger();
        MqttServer mqttServer;
        public async Task Start()
        {
            var mqttFactory = new MqttFactory();
            // Due to security reasons the "default" endpoint (which is unencrypted) is not enabled by default!x
            var mqttServerOptions = mqttFactory.
                CreateServerOptionsBuilder().
                WithDefaultEndpoint().
                Build();
            var server = mqttFactory.CreateMqttServer(mqttServerOptions);
            if (server == null)
            {
                logger.Fatal("【MQTTBroker】MQTT服务器启动失败，请检查运行环境！");
                return;
            }
            server.ClientConnectedAsync += MqttServer_ClientConnectedAsync;
            server.ClientDisconnectedAsync += MqttServer_ClientDisconnectedAsync;
            server.ValidatingConnectionAsync += MqttServer_ValidatingConnectionAsync;
            await server.StartAsync();
            logger.Info("【MQTTBroker】启动完成！");
        }
        private Task MqttServer_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg)
        {
            arg.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.Success;
            return Task.CompletedTask;
        }



        private Task MqttServer_ClientDisconnectedAsync(ClientDisconnectedEventArgs x)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"【MQTTBroker】设备下线: ID: [{x.ClientId}], Endpoint: [{x.Endpoint}] 的用户已断开连接！");
            logger.Info(sb.ToString());
            return Task.CompletedTask;
        }

        private Task MqttServer_ClientConnectedAsync(ClientConnectedEventArgs x)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("【MQTTBroker】设备上线: 来自 ");
            sb.Append("Name: " + x.UserName == null ? "未知" : x.UserName + ", ");
            sb.Append("Version: " + x.ProtocolVersion.ToString() + ", ");
            sb.Append("ClientID: " + x.ClientId + ", ");
            sb.Append("EndPoint: " + x.Endpoint);
            sb.Append("的用户已连接！");
            logger.Info(sb.ToString());
            return Task.CompletedTask;
        }
    }
}
